package cn.edu.zsc.rbac.service.array;

import cn.edu.zsc.rbac.domain.entity.Dept;
import cn.edu.zsc.rbac.domain.dto.DeptDto;
import cn.edu.zsc.rbac.domain.vo.DeptVo;
import cn.edu.zsc.rbac.domain.vo.Result;
import cn.edu.zsc.rbac.service.IBaseService;
import cn.edu.zsc.rbac.service.IDeptService;
import cn.edu.zsc.rbac.service.IUserService;

import java.util.Arrays;

/**
 * 业务层-部门
 *
 * @author
 * @since 2025/4/18 15:20
 */
public class DeptService extends BaseService<Dept,DeptDto>implements IDeptService {


    private IUserService userService;

    private static IDeptService singleton;

    private DeptService() {
        data=new Dept[DATA_SIZE];

    }

    public static IDeptService getInstance(){
        if(singleton==null){
            singleton=new DeptService();
        }
        return singleton;
    }



    public  DeptVo convert(Dept dept){

        return new DeptVo(dept.getId(),dept.name,dept.phone);
    }
    public  Dept createEntity(DeptDto dto,int id){

        return new Dept(id,dto.name,dto.phone);
    }
    public  void updateEntity(DeptDto dto,Dept dept){
        dept.name=dto.name;
        dept.phone=dto.phone;
    }


    @Override
    public  Result list(){
        DeptVo[] temp=new DeptVo[DATA_SIZE];
        int length=0;
        for (int i = 0; i < idCounter; i++) {
            if(data[i]!=null){
                temp[length++]=convert(data[i]);
            }
        }
        return Result.success("查询成功",Arrays.copyOf(temp,length));
    }

    @Override
    public  Result create(DeptDto dto) {
        if(idCounter>DATA_SIZE){
            return Result.failure("创建失败，超出了存储容量");
        }
//        Dept dept = new Dept(dto.name, dto.phone);
//        dept.id=idCounter++;
        Dept dept = createEntity(dto,idCounter++);
        data[dept.getId()]=dept;
        return Result.success("创建成功",null);
    }

    @Override
    public  Result update(DeptDto dto,int id) {
        if (!existsById(id)) {
            return Result.failure("更新失败，不存在该数据");
        }
        Dept dept=data[id];
        updateEntity(dto,dept);
        return Result.success("更新成功", null);
    }

    @Override
    public  Result delete(int id) {
        if (!existsById(id)) {
            return Result.failure("删除失败，不存在该数据");
        }
        if(userService==null){
            userService=UserService.getInstance();
        }
        if(userService.deptInUse(id)){
            return Result.failure("删除失败，还有用户属于部门，不能删除");
        }
        data[id]=null;
        return Result.success("删除成功", null);
    }


}
